package com.example.threadcode.higherLeverTwo.CountDownLatchDemo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 默认主线程首先创建一对CountDownLatch.
 * startSignal阻止任何工作线程对程序的处理,直到默认主线程对他们的处理准备好
 * doneSignal 他会导致默认主线程进入等待直到所有工作线程完成工作把他里面的计数减到0才会释放默认主线程让程序终止
 *
 */
public class CountDownLatchDemo
{
   final static int NTHREADS = 3;

   public static void main(String[] args)
   {
      final CountDownLatch startSignal = new CountDownLatch(1);
      final CountDownLatch doneSignal = new CountDownLatch(NTHREADS);
      Runnable r = new Runnable()
                   {
                      @Override
                      public void run()
                      {
                         try
                         {
                            report("entered run()");
//                           把所有线程等待
                            startSignal.await();  // wait until told to ...
//                            这里的执行需要startSignal计数器数到0才能往下执行
                            report("doing work"); // ... proceed
                            Thread.sleep((int) (Math.random() * 1000));
//                            三个工作线程,每个来减一次就减到0了,那么就释放主线程让应用终止了
                            doneSignal.countDown(); // reduce count on which
                                                    // main thread is ...
                         }                          // waiting
                         catch (InterruptedException ie)
                         {
                            System.err.println(ie);
                         }
                      }

                      void report(String s)
                      {
                         System.out.println(System.currentTimeMillis() + 
                                            ": " + Thread.currentThread() + 
                                            ": " + s);
                      }
                   };
      ExecutorService executor = Executors.newFixedThreadPool(NTHREADS);
      for (int i = 0; i < NTHREADS; i++)
         executor.execute(r);
      try
      {
         System.out.println("main thread doing something");
         Thread.sleep(10000); // sleep for 1 second
//        startSignal减1次就变成0了,等待中的三条线程就被释放了
         startSignal.countDown(); // let all threads proceed
         System.out.println("main thread doing something else");
//        主线程跑到这就被doneSignal给暂停了.然后必须等里面计数读到0才会释放
         doneSignal.await(); // wait for all threads to finish
         executor.shutdownNow();
      }
      catch (InterruptedException ie)
      {
         System.err.println(ie);
      }
   }
}